package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Damage;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.ClaimItemMapper;
import cn.wolfcode.crm.mapper.ClientClaimMapper;
import cn.wolfcode.crm.mapper.DamageMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDamageService;
import cn.wolfcode.crm.util.LogicException;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class DamageServiceImpl implements IDamageService {
    @Autowired
    private DamageMapper damageMapper;
    @Autowired
    private ClaimItemMapper claimItemMapper;
    @Autowired
    private ClientClaimMapper clientClaimMapper;


    public List<Damage> selectAll() {
        return damageMapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int count = damageMapper.query4Count(qo);
        if (count > 0) {
            return new PageResult(count, damageMapper.query4List(qo));
        }
        return new PageResult(count, Collections.EMPTY_LIST);
    }

    public void updateByPrimaryKey(Damage record) {
        Damage damage = damageMapper.selectByPrimaryKey(record.getId());
        if (damage.getState() == true){
            throw new LogicException("该保单已经拨款成功,无法修改");
        }
        Employee currentUser = UserContext.getCurrentUser();
        record.setEmployee(currentUser);
        record.setDisposeTime(new Date());
        damageMapper.updateByPrimaryKey(record);
    }

    public void insert(Damage record) {
        damageMapper.insert(record);
    }

    public void changeState(Long id) {
        Damage damage = damageMapper.selectByPrimaryKey(id);
        if (damage.getMoney()==null){
            throw new LogicException("请先处理赔损明细");
        }
        if (damage.getState()){
            throw new LogicException("该单已经拨款");
        }
        damageMapper.changeState(id);

        Long claimId = damageMapper.selectClaimIdByDamageId(id);
        Long claimItemId = claimItemMapper.selectClaimItemIdByClaimId(claimId);

        clientClaimMapper.insertBy3Id(claimId,claimItemId,id);

    }


}
